<template>
  <div class="sku-management">
    <div style="padding: 16px 0;">
      <el-page-header @back="goBack" :content="headerTitle"></el-page-header>
    </div>
    <!-- -->
    <el-form ref="formRefs" :rules="formRules" :model="formData" label-width="140px">
      <!-- 商品基本信息 -->
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="formData.name" placeholder="商品名称" :disabled="headerTitle === '商品详情'"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brand_id">
            <el-select v-model="formData.brand_id" placeholder="请选择品牌" style="width: 100%;"
              :disabled="headerTitle === '商品详情'">
              <el-option v-for="brand in brands" :key="brand.id" :label="brand.name" :value="brand.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="分类" prop="category_id">
            <el-cascader v-model="formData.category_id" :options="categories" :props="optionProps" style="width: 100%;"
              popper-class="popper-select" :disabled="headerTitle === '商品详情'"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品单位" prop="unit">
            <el-input v-model="formData.unit" placeholder="请输入商品单位" :disabled="headerTitle === '商品详情'"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 规格管理 -->
      <el-form-item label="商品规格" prop="spec_info">
        <div v-for="(spec, index) in formData.spec_info" :key="index" class="spec-item">
          <el-input v-model="spec.spec_name" placeholder="规格名称" style="width: 150px"
            :disabled="headerTitle === '商品详情'"></el-input>
          <span>：</span>
          <el-select v-model="spec.spec_value" multiple filterable allow-create default-first-option
            placeholder="请输入规格值" style="width: 400px" :disabled="headerTitle === '商品详情'">
            <el-option v-for="(item, i) in spec.spec_value" :key="i" :label="item" :value="item"></el-option>
          </el-select>
          <el-button @click="removeSpec(index)" type="danger" icon="el-icon-delete" circle size='mini'
            v-if="headerTitle !== '商品详情'"></el-button>
        </div>
        <div>
          <el-button type="primary" icon="el-icon-plus" size='mini' @click="addSpec"
            :disabled="headerTitle === '商品详情'">添加规格</el-button>
          <el-button type="primary" size='mini' @click="generateSku"
            :disabled="headerTitle === '商品详情'">生成SKU</el-button>
        </div>

      </el-form-item>

      <!-- SKU表格 -->
      <el-form-item label="SKU管理" v-if="formData.sku_info.length > 0" prop="sku_info">
        <el-table :data="formData.sku_info" border style="width: 100%">
          <el-table-column label="SKU组合">
            <template slot-scope="scope">
              <div v-for="(spec, index) in scope.row.spec_info" :key="index">
                {{ spec.spec_name }}: {{ spec.spec_value }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="编码">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sku_code" placeholder="编码" :disabled="headerTitle === '商品详情'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="零售价">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" placeholder="零售价" :disabled="headerTitle === '商品详情'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="会员价">
            <template slot-scope="scope">
              <el-input v-model="scope.row.member_price" placeholder="会员价"
                :disabled="headerTitle === '商品详情'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stock" placeholder="库存" :disabled="headerTitle === '商品详情'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="进价">
            <template slot-scope="scope">
              <el-input v-model="scope.row.buy_price" placeholder="进价" :disabled="headerTitle === '商品详情'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="批发价">
            <template slot-scope="scope">
              <el-input v-model="scope.row.trade_price" placeholder="批发价" :disabled="headerTitle === '商品详情'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="SKU图片" width="160">

            <template slot-scope="scope">
              <el-upload class="sku-uploader" :action="uploadUrl" :headers="uploadHeaders" :data="uploadData"
                :show-file-list="false" :on-success="(res, file) => handleUploadSuccess(res, file, scope.$index)"
                :before-upload="(file) => beforeUpload(file, scope.$index)" :disabled="headerTitle === '商品详情'">
                <img v-if="scope.row.picture" :src="scope.row.picture" class="sku-image">
                <i v-if="scope.row.picture && headerTitle !== '商品详情'" class="el-icon-delete-solid delete-file"
                  @click.stop="removeImage(scope.$index)"></i>
                <i v-if="!scope.row.picture && headerTitle !== '商品详情'" class="el-icon-plus sku-uploader-icon"></i>
              </el-upload>
              <div class="el-upload__tip">建议尺寸: 800x800像素</div>

            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" active-color="#409EFF"
                inactive-color="#d2d6de" active-text="上架" inactive-text="下架" :disabled="headerTitle === '商品详情'">
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- 其他信息 -->
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="封面图片" prop="cover_picture">
            <Upload :fileList.sync="formData.cover_picture" :accept="'image/*'" :limit="9" fileSize="10" multiple
              :fileType="1" @update:fileList="updateCoverFileList" :disabled="headerTitle === '商品详情'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="视频" prop="video">
            <Upload :fileList.sync="formData.video" :accept="'video/*'" :limit="9" fileSize="10" multiple :fileType="2"
              @update:fileList="updateVideoFileList" :disabled="headerTitle === '商品详情'" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="相册图片" prop="album">
            <Upload :fileList.sync="formData.album" :accept="'image/*'" :limit="9" fileSize="10" multiple :fileType="1"
              @update:fileList="updateAlbumFileList" :disabled="headerTitle === '商品详情'" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="基础价格" prop="base_price">
            <el-input type="number" placeholder="请输入基础价格" v-model="formData.base_price"
              :disabled="headerTitle === '商品详情'">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员基础价格" prop="member_base_price">
            <el-input type="number" placeholder="请输入会员基础价格" v-model="formData.member_base_price"
              :disabled="headerTitle === '商品详情'">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="是否售卖商品" prop="is_sell">
            <el-radio-group v-model="formData.is_sell" :disabled="headerTitle === '商品详情'">
              <el-radio :label="0">采购商品</el-radio>
              <el-radio :label="1">售卖商品</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%;"
              :disabled="headerTitle === '商品详情'">
              <el-option v-for="item in dicData" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="一级分销佣金比例" prop="one_level_income_rate">
            <el-input type="number" v-model="formData.one_level_income_rate" :max="1" :min="0" :step="0.01"
              :disabled="headerTitle === '商品详情'">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="二级分销佣金比例 " prop="two_level_income_rate">
            <el-input type="number" v-model="formData.two_level_income_rate" :max="1" :min="0" :step="0.01"
              :disabled="headerTitle === '商品详情'">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="商品描述" prop="detail">
            <el-input type="textarea" :rows="4" placeholder="请输入商品描述" v-model="formData.detail"
              :disabled="headerTitle === '商品详情'">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogVisible" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>

import { getAllBrandList } from '../../brand/api/brand'
import { getProductCategoryList } from '../../productCategory/api/productCategory'
import { getProductItemDetail, updateProductItem } from "../api/product";
import Upload from './upload.vue'
import { getToken } from "@/util/auth";
export default {
  components: {
    Upload
  },
  data () {
    const validateSpecInfo = (rule, value, callback) => {
      console.log("长度：", value.length);
      if (!value) {
        callback(new Error("请添加商品规格"));
      } else {
        callback()
      }
    };
    return {
      headerTitle: '',
      dialogVisible: false,
      dialogImageUrl: '',
      uploadUrl: '/admin/common/upload', // 上传接口
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadData: {
        type: 'sku'
      },
      filePathPrefix: $imgBaseUrl,
      dicData: [{
        label: '上架',
        value: 0
      }, {
        label: '下架',
        value: 1
      }],
      brands: [], // 品牌列表
      categories: [], // 分类列表
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true
      },
      formData: {
        id: "", // 商品ID,编辑时必传
        brand_id: "", // 品牌
        category_id: "", // 分类
        name: "", // 名称
        unit: "", // 单
        cover_picture: [], // 封面
        album: [], // 相册
        video: [], // 视频
        detail: "", // 详情
        base_price: "", // 基础价格
        member_base_price: "", // 会员基础
        status: "", // 状态
        spec_info: [], // 规格信息 规格ID,编辑时必传
        sku_info: [], // 	sku信息 skuID,编辑时必传
        is_sell: "", // 是否售卖商品
        one_level_income_rate: "", // 一级分销佣金比例
        two_level_income_rate: "" // 二级分销佣金比例
      },
      formRules: {
        name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        brand_id: [
          {
            required: true,
            message: "请选择商品品牌",
            trigger: "change"
          },
        ],
        category_id: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "change"
          },
        ],
        cover_picture: [
          {
            required: true,
            message: "请选择封面图片",
            trigger: "change"
          },
        ],
        album: [
          {
            required: true,
            message: "请选择相册图片",
            trigger: "change"
          },
        ],
        detail: [
          {
            required: true,
            message: "请输入商品详情",
            trigger: "blur",
          },
        ],
        base_price: [
          {
            required: true,
            message: "请输入基础价格",
            trigger: "blur",
          },
        ],
        member_base_price: [
          {
            required: true,
            message: "请输入会员基础价格",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择商品状态",
            trigger: "change"
          },
        ],
        is_sell: [
          {
            required: true,
            message: "请选择是否售卖商品",
            trigger: "change"
          },
        ],
        one_level_income_rate: [
          {
            required: true,
            message: "请输入一级分销佣金比例",
            trigger: "blur"
          },
        ],
        two_level_income_rate: [
          {
            required: true,
            message: "请输入二级分销佣金比例",
            trigger: "blur"
          },
        ],
        spec_info: [
          {
            required: true,
            validator: validateSpecInfo,
            trigger: "change"
          },
        ],
      },
    };
  },

  created () {
    // 初始化数据或从API获取已有数据
    this.initData();
  },
  methods: {
    // SKU 图片上传 start
    beforeUpload (file, index) {
      const isImage = file.type.includes('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!');
        return false;
      }

      // 保存文件对象到对应的SKU项
      this.formData.sku_info[index].picture = URL.createObjectURL(file); // URL.createObjectURL(file);

      return true;
    },

    handleUploadSuccess (res, file, index) {
      if (res.err === 0) {
        this.$set(this.formData.sku_info, index, {
          ...this.formData.sku_info[index],
          picture: this.filePathPrefix + res.data.file
        });
        this.$forceUpdate();
        this.$message.success('上传成功');
      } else {
        this.$message.error(res.message || '上传失败');
      }
    },

    removeImage (index) {
      this.$set(this.formData.sku_info, index, {
        ...this.formData.sku_info[index],
        picture: '',
        picture: null
      });
    },
    // SKU 图片上传 end
    updateCoverFileList (val) {
      // console.log('封面图片', val);
      this.formData.cover_picture = val
      this.$refs.formRefs.validateField('cover_picture') //  // 重新验证该字段
    },
    updateAlbumFileList (val) {
      // console.log('相册图片', val);
      this.formData.album = val
      this.$refs.formRefs.validateField('album') //  // 重新验证该字段
    },
    updateVideoFileList (val) {
      // console.log('视频', val);
      this.formData.video = val

    },
    // 获取商品分类
    initProductCategoryData () {
      getProductCategoryList({ type: 1 }).then(
        (res) => {
          this.categories = res.data
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    // 获取所有品牌
    initAllBrandData () {
      getAllBrandList({}).then(
        (res) => {
          this.brands = res.data
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    initData () {
      // 用API获取品牌和分类数据
      this.initAllBrandData()
      this.initProductCategoryData()
      // 示例数据
      // this.brands = [
      //   { id: 1, name: "品牌1" },
      //   { id: 2, name: "品牌2" }
      // ];

      // this.categories = [
      //   { id: 1, name: "分类1", children: [
      //     { id: 11, name: "子分类1" },
      //     { id: 12, name: "子分类2" }
      //   ]},
      //   { id: 2, name: "分类2" }
      // ];

      // 如果有编辑的商品ID，可以在这里获取商品详情
      if (this.$route.query && this.$route.query.queryId) {
        this.headerTitle = this.$route.query.type === 'update' ? "编辑商品" : '商品详情'
        this.getProductDetail(this.$route.query.queryId);

      } else {
        this.headerTitle = "新增商品"
      }
    },

    // 添加规格
    addSpec () {
      this.formData.spec_info.push({
        id: "",
        spec_name: "",
        spec_value: []
      });
    },

    // 删除规格
    removeSpec (index) {
      this.formData.spec_info.splice(index, 1);
      // 删除规格后需要重新生成SKU
      this.generateSku();
    },

    // 生成SKU组合
    generateSku () {
      if (this.formData.spec_info.length === 0) {
        this.formData.sku_info = [];
        return;
      }

      // 生成所有可能的SKU组合
      let skus = this.cartesianProduct(this.formData.spec_info);

      // 更新或创建SKU信息
      let newSkuInfo = skus.map(sku => {
        // 检查是否已存在相同的SKU
        let existingSku = this.formData.sku_info.find(item => {
          return this.isSameSku(item.spec_info, sku);
        });

        if (existingSku) {
          // 保留已有的SKU信息
          return {
            ...existingSku,
            spec_info: sku
          };
        } else {
          // 创建新的SKU
          return {
            id: "",
            sku_code: '', //this.generateSkuCode(),
            spec_info: sku,
            price: "",
            member_price: "",
            buy_price: "",
            trade_price: "",
            stock: "",
            picture: "",
            status: ""
          };
        }
      });

      this.formData.sku_info = newSkuInfo;
    },

    // 生成笛卡尔积
    cartesianProduct (specs) {
      return specs.reduce((acc, currentSpec) => {
        if (!currentSpec.spec_value || currentSpec.spec_value.length === 0) {
          return acc;
        }

        if (acc.length === 0) {
          return currentSpec.spec_value.map(value => [
            {
              id: "",
              spec_name: currentSpec.spec_name,
              spec_value: value
            }
          ]);
        }

        let result = [];
        for (let i = 0; i < acc.length; i++) {
          for (let j = 0; j < currentSpec.spec_value.length; j++) {
            result.push([
              ...acc[i],
              {
                id: "",
                spec_name: currentSpec.spec_name,
                spec_value: currentSpec.spec_value[j]
              }
            ]);
          }
        }
        return result;
      }, []);
    },

    // 检查两个SKU是否相同
    isSameSku (sku1, sku2) {
      if (sku1.length !== sku2.length) return false;

      for (let i = 0; i < sku1.length; i++) {
        if (sku1[i].spec_name !== sku2[i].spec_name ||
          sku1[i].spec_value !== sku2[i].spec_value) {
          return false;
        }
      }

      return true;
    },

    // 生成SKU编码
    generateSkuCode () {
      return 'SKU' + Date.now().toString(36) + Math.random().toString(36).substr(2, 5).toUpperCase();
    },

    goBack () {
      this.$router.go(-1) //  go()后退+刷新 back()后退
    },
    // 去掉图片地址前缀
    getStringAfter (str, search) {
      const index = str.indexOf(search);
      if (index === -1) return "";
      return str.substring(index + search.length);
    },
    // 提交表单
    submitForm () {
      // 验证表单
      this.$refs.formRefs.validate(valid => {
        if (valid) {
          // 处理数据
          let submitData = JSON.parse(JSON.stringify(this.formData));
          // 分类ID
          submitData.category_id = typeof submitData.category_id === 'object' ? submitData.category_id[submitData.category_id.length - 1] : submitData.category_id
          // 转换图片数据为服务器需要的格式
          submitData.cover_picture = submitData.cover_picture.map(item => this.getStringAfter(item, this.filePathPrefix));
          submitData.album = submitData.album.map(item => this.getStringAfter(item, this.filePathPrefix));

          // 如果有视频，也需要处理
          if (submitData.video && submitData.video.length > 0) {
            submitData.video = submitData.video.map(item => this.getStringAfter(item, this.filePathPrefix));
          }

          // sku
          if (submitData.sku_info && submitData.sku_info.length > 0) {
            submitData.sku_info = submitData.sku_info.map(item => {
              return {
                ...item,
                picture: this.getStringAfter(item.picture, this.filePathPrefix)
              }
            });
          }
          // 规格信息
          let specInfo = []
          if (submitData.sku_info && submitData.sku_info.length > 0) {
            submitData.sku_info.forEach(item => {
              specInfo.push(item.spec_info[0])
            });
          }
          submitData.spec_info = specInfo;
          // 调用API提交数据
          console.log("提交的数据:", submitData);
          this.saveProduct(submitData);
        } else {
          this.$message.error('请填写完整信息！');
          return false;
        }
      });
    },

    // 保存商品API调用
    saveProduct (data) {
      // 这里调用实际的API
      updateProductItem(data).then(res => {
        this.$message.success('保存成功');
        this.goBack()
      })
    },

    // 获取商品详情API调用
    getProductDetail (id) {
      getProductItemDetail({ id }).then(res => {
        console.log(1, '获取商品详情：', res.data);

        this.formData = { ...res.data };
        this.formData.spec_info = this.formatProductSpecification(res.data.productSpecification);
        this.formData.sku_info = res.data.productSku && res.data.productSku.map(item => {
          return {
            ...item,
            picture: this.filePathPrefix + item.picture
          }
        });
        // this.filePathPrefix: $imgBaseUrl
        this.formData.album = res.data.album && res.data.album.map(item => { return this.filePathPrefix + item }) || [];
        this.formData.cover_picture = res.data.cover_picture && res.data.cover_picture.map(item => { return this.filePathPrefix + item }) || [];
        this.formData.video = res.data.video && res.data.video.map(item => { return this.filePathPrefix + item }) || [];

      })
    },
    formatProductSpecification (originalData) {
      // 按 spec_name 分组并合并 spec_value
      const grouped = {};
      originalData.forEach(item => {
        const key = item.spec_name;
        if (!grouped[key]) {
          grouped[key] = {
            id: item.id,
            product_id: item.product_id,
            spec_name: item.spec_name,
            spec_value: []
          };
        }
        grouped[key].spec_value.push(item.spec_value);
      });

      // 转换为数组
      const result = Object.values(grouped);
      console.log(result);
      return result

    }
  }
};
</script>
<style scoped>
.delete-file {
  cursor: pointer;
  font-size: 14px;
  color: #f56c6c;
  position: absolute;
  top: 2px;
  right: 2px;
}

.sku-uploader {
  display: inline-block;
}

.sku-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.sku-uploader ::v-deep .el-upload:hover {
  border-color: #409EFF;
}

.sku-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.sku-image {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
<style scoped>
.sku-management {
  padding: 20px;
}

.spec-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.spec-item .el-input {
  margin-right: 10px;
}

.spec-item .el-select {
  margin-right: 10px;
}

.sku-image {
  width: 100px;
  height: 100px;
  display: block;
}

.sku-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}


.sku-uploader .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.sku-uploader .el-upload-list__item {
  width: 100px;
  height: 100px;
}
</style>

<style>
::v-deep .popper-select {
  /* li[aria-haspopup="true"] {
    .el-checkbox {
      display: none;
    }
  } */
}
</style>
